<template>
  <el-dialog width="500px" title="更改设备编号" :visible.sync="dialogVisible" :close-on-click-modal="false">
    <el-form ref="ruleForm" :model="form" label-width="100px">
      <el-form-item label="订单编号">
        <el-input v-model="form.orderId" disabled />
      </el-form-item>
      <template v-for="(item, index) in form.deviceNumber">
        <el-form-item :key="index" :label="item.label" :rules="deviceRule.value" :prop="'deviceNumber.' + index + '.value'">
          <el-input v-model="item.value" clearable />
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="dialogVisible = false">取 消</el-button>
      <el-button size="small" type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { setDeviceNumber } from '@/api/order'
export default {
  // props: ['editItem'],
  props: {
    editItem: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        orderId: '',
        deviceNumber: []
      },
      dialogVisible: false,
      deviceRule: {
        value: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }]
      }
    }
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        const { orderId, deviceNumber, amount } = this.editItem
        this.form.orderId = orderId
        this.form.deviceNumber = []
        for (let i = 0; i < amount; i++) {
          const obj = {
            label: '设备编号' + (i + 1),
            value: deviceNumber[i] || ''
          }
          this.form.deviceNumber.push(obj)
        }
      } else {
        this.$refs['ruleForm'].resetFields()
      }
    }
  },
  methods: {
    submit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const params = { ...this.form }
          params.deviceNumber = params.deviceNumber ? params.deviceNumber.map(item => item.value).join(',') : ''
          setDeviceNumber(params).then(res => {
            this.dialogVisible = false
            this.$emit('getList', true)
          })
        } else {
          this.$message({
            message: '请检查表单错误',
            type: 'error'
          })
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
